//
//  ST_TIANAlertDispatchComponent.swift
//  btvideo
//
//  Created by Jason on 2021/12/9.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import SwiftyJSON
import RxSwift
import SwiftyUserDefaults
import RxRelay

/// 当前状态
enum ST_TIANAlertTaskStatus{
    case waiting
    case err
    case pulled
    case toasting
    case finished
    case skip
}

/// 类型
enum ST_TIANAlertType {
    case loginReward
    case someoneRecommended
    /// 每日礼物奖励 [完成任务]
    case taskFinished
    /// 新年快乐活动
    case happyNewYear
}






class ST_TIANAlertData {
    
    let type:ST_TIANAlertType
    var status:ST_TIANAlertTaskStatus
    var json:JSON?
    var nextAlert:ST_TIANAlertData?
    
    
    init(type:ST_TIANAlertType,status:ST_TIANAlertTaskStatus,json:JSON? = nil,nextAlert:ST_TIANAlertData? = nil) {
        
        self.type = type
        self.status = status
        self.json = json
        
        self.nextAlert = nextAlert
    }
    
    private func toast(){
        
        guard let eJson = json,status == .pulled || status == .skip else {
            return
        }
        
        switch type {
        case .loginReward:
            
            print("Alert Queue -- 登录礼物🎁弹窗!!")
            
            let alert = ST_LoginForGiftController()
            alert.json = eJson
            alert.overCurrentContext = true
            alert.over_current_context_alpha = "0.4"
            GlobalPresent(toController: alert)
            
        case .someoneRecommended:
            
            print("Alert Queue -- 推荐某人弹窗!!")
            
            ST_MediaChatDispatcher.shared.live_alert_accid_set.update(with: eJson["data"]["accid"].stringValue)
            
            let vc = CupidFactory.currency(for: eJson["data"], cupidType: .recommendSomeOne)
            
            GlobalPresent(toController: vc)
            
        case .taskFinished:
            
            print("Alert Queue -- 任务完成弹窗!!")
            
            if let vc = SCComponets.alert_dispatcher?.current_reward_v_c{
                vc.rotateTo(json: eJson)
            }else{
                let vc = ST_DailyFinishedRewardController(taskJson: eJson)
                GlobalPresent(toController: vc)
                SCComponets.alert_dispatcher?.current_reward_v_c = vc
            }
            
        case .happyNewYear:
            
            GlobalPresent(toController: ST_TimedRewardController(rewardJson: eJson))
        }
        
        self.status = .toasting
        
    }
    
}

extension ST_TIANAlertData{
    
    /// 添加到最后一个
    func appendToFinally(_ data:ST_TIANAlertData){
        
        var finallyAlert = self
        
        while finallyAlert.nextAlert != nil {
            finallyAlert = finallyAlert.nextAlert!
        }
        
        finallyAlert.nextAlert = data
        
    }
    
    /// 当前正在弹窗的数据
    class func foundToastingItem(alert:ST_TIANAlertData)->ST_TIANAlertData?{
        
        if alert.status == .toasting{
            return alert
        }else if let next = alert.nextAlert{
            return foundToastingItem(alert: next)
        }else{
            return nil
        }
        
    }
    
    /// 扫描
    fileprivate func explore(){
        
        switch status {
        case .finished,.err:
            
            /// 当前如果有下一级，则弹窗下一级
            if let next = nextAlert{
                
                /// 下一级 不是每日礼物奖励  则关闭领取每日奖励的VC
                if let current_reward_v_c = SCComponets.alert_dispatcher?.current_reward_v_c,  next.type != .taskFinished{
                    current_reward_v_c.goback_previous_controller(animated: true) {
                        next.explore()
                    }
                }else{
                    next.explore()
                }
            }
            /// 没有下一级 则关闭领取每日奖励的VC
            else{
                SCComponets.alert_dispatcher?.current_reward_v_c?.goback_previous_controller()
            }
            
        case .pulled,.skip:
            toast()
        default : break
        }
    }
}


/// 弹窗管理/派遣类
class ST_TIANAlertDispatchComponent: NSObject {

    private let myInfo:ST_BTUserinfo
    
    private var rootAlert:ST_TIANAlertData?
    
    ///当前的每日任务、新手任务 领取界面
    fileprivate weak var current_reward_v_c:ST_DailyFinishedRewardController?
    
    ///当前的每日任务、新手任务 领取🆔 去重使用
    private var reward_id_set = Set<String>()
    
    /// true  当前不适合弹窗 , 默认false
    var waiting_status = BehaviorRelay<Bool>(value: false)
    
    deinit {
        print("Alert Queue --  切换账户一定要调用")
    }
    
    init(myInfo:ST_BTUserinfo) {
        
        print("Alert Queue -- 主键初始化!")
        
        self.myInfo = myInfo
        super.init()
        
        if myInfo.sex == .male{
            
            rootAlert = ST_TIANAlertData(type: .loginReward, status: .waiting, nextAlert: ST_TIANAlertData(type: .someoneRecommended, status: .waiting, nextAlert: nil))
            
            assemble_signal()
        }
        
        binding()
        
    }
    
    /// value 指定开始扫描的数据源  = nil 从最开始扫描
    private let alert_publisher = PublishSubject<ST_TIANAlertData?>()
    
    
    private var recommendKey:String{
        return "myDateToday_"+myInfo.accid+"28943849"
    }
    private var canRecommend:Bool{

        if let lastDate = Defaults.date(forKey: recommendKey){

            #if DEBUG
            //            有值 并且超过4分钟
            if lastDate.timeIntervalSinceNow.abs < 2*60{
                return true
            }
            #else
            //            有值 并且是今天
            if lastDate.isInToday{
                return true
            }
            #endif
        }

        return false
    }
    
    
    private func binding(){
        
        Observable.combineLatest(alert_publisher, waiting_status,ST_BTLaunchController.shared.advertStatus).withUnretained(self).subscribe(onNext: { own,arg in
            
            if arg.1 == false && arg.2 != .displaying{
                if let launchAlert = arg.0{
                    launchAlert.explore()
                }else{
                    own.rootAlert?.explore()
                }
            }
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    /// 请求数据 合并信号📶
    private func assemble_signal(){
        
        if canRecommend{
            
            Observable.zip(TIANSession(requestUrl: PH.loginRewardApi),TIANSession(requestUrl: PH.getRecommendOneApi)).delay(RxTimeInterval.seconds(9), scheduler: MainScheduler.instance).withUnretained(self).subscribe(onNext: { own,arg in
                
                let result0 = arg.0
                let result1 = arg.1
                
                switch result0 {
                case .success(let json):
                    
                    print("Alert Queue - loginRewardApi json222 =",json)
                    
                    if json["data"].dictionaryValue.keys.count < 1{
                        own.rootAlert?.status = .err
                    }else{
                        own.rootAlert?.json = json
                        own.rootAlert?.status = .pulled
                    }
                default:
                    own.rootAlert?.status = .err
                    print("Alert Queue - loginRewardApi json222 status err")
                }
                
                switch result1 {
                case .success(let json):
                    own.rootAlert?.nextAlert?.json = json
                    own.rootAlert?.nextAlert?.status = .pulled
                default:
                    own.rootAlert?.nextAlert?.status = .err
                }
                
                own.alert_publisher.onNext(nil)
                
            }).disposed(by: rx.disposeBag)
            
        }else{
            
            TIANSession(requestUrl: PH.loginRewardApi).delay(RxTimeInterval.seconds(9), scheduler: MainScheduler.instance).withUnretained(self).subscribe(onNext: { own,result in
                
                
                switch result {
                case .success(let json):
                    
                    print("Alert Queue - loginRewardApi json =",json)
                    
                    if json["data"].dictionaryValue.keys.count < 1{
                        own.rootAlert?.status = .err
                    }else{
                        own.rootAlert?.json = json
                        own.rootAlert?.status = .pulled
                    }
                default:
                    own.rootAlert?.status = .err
                    print("Alert Queue - loginRewardApi json status err")
                }
                
                own.rootAlert?.nextAlert?.status = .err
                
                own.alert_publisher.onNext(nil)
                
            }).disposed(by: rx.disposeBag)
            
        }
        
        
    }
}


extension ST_TIANAlertDispatchComponent{
    
    /// 下一个alert
    /// jump  == true 没有领取，下次领取
    func nextAlert(jump:Bool = false){
        
        
        guard let currentAlert = self.rootAlert,let found = ST_TIANAlertData.foundToastingItem(alert: currentAlert) else{
            
    /// 扫描完成之后 ,关闭 领取任务奖励的VC
            SCComponets.alert_dispatcher?.current_reward_v_c?.goback_previous_controller()
            
            return
        }
        
        if jump{
            found.status = .skip
        }else{
            found.status = .finished
        }
        
        if let nextAlertValue = found.nextAlert{
            alert_publisher.onNext(nextAlertValue)
        }else{
                /// 扫描完成之后,没有新的弹窗 ,关闭 领取任务奖励的VC
            SCComponets.alert_dispatcher?.current_reward_v_c?.goback_previous_controller()
        }
        
    }
    
    /// 接收到新年礼物 奖励弹窗数据
    func receive_happy_new_year_award(itemJson:JSON){
        
        let item = ST_TIANAlertData(type: .happyNewYear, status: .pulled, json: itemJson, nextAlert: nil)
        
        if let root = self.rootAlert{
            root.appendToFinally(item)
        }else{
            self.rootAlert = item
        }
        
        alert_publisher.onNext(nil)
    }
    
    /// 接收到 任务奖励弹窗数据
    func receive_award_task(array:[JSON]){
        
        /// 去重
        let list = array.filter{ !reward_id_set.contains($0["id"].stringValue) }
        
        list.map{ ST_TIANAlertData(type: .taskFinished, status: .pulled, json: $0, nextAlert: nil) }.forEach { item in
        
            if let root = self.rootAlert{
                root.appendToFinally(item)
            }else{
                self.rootAlert = item
            }
            
            if let itemJson = item.json{
                /// 📝记录🆔
                self.reward_id_set.update(with: itemJson["id"].stringValue)
            }
        }
        
        alert_publisher.onNext(nil)
    }
    
    /// 出发礼物推送
    func request_award_sync(){
        
        TIANSession(requestUrl: PH.awardTriggerApi).subscribe(onNext: { _ in
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    
    /// 今日推荐 频率控制
    func finish_recommend_one_stack(){
        
        Defaults.set(true, forKey: recommendKey)
        
    }
    
}
